const bleManager = require('../../utils/BLE/CRBleManager.js')
import api from '../../../api/index'

Page({
	/**
   * 页面的初始数据
   */
	data: {
		bindDeviceId: null,
		devicelist: [],
		showDevice: false,
		actions: [],
		bindDevice: [],
		saveDevice: {},
		showDialog: false,
		bindDeviceTextInfo: '',
		loading: false,
		bleAvaible: true
	},

	/**
   * 生命周期函数--监听页面加载
   */
	onLoad(options) {
		this.get()
  },
  // 蓝牙初始化
  doInitBlue() {
    bleUtils.initBlueTooth().then((res) => {
			this.setData({
				bleAvaible: true
			})
      this.doGetBluetoothAdapterState()
    }).catch(error => {
			this.setData({
				bleAvaible: false
			})
		})
  },
	// 链接设备
	goBindEq() {
		
		this.setBleCallBack()
	},
  setBleCallBack (){
    const that = this
    //蓝牙管理
    bleManager.setDelegate({
        //搜索结束
        SearchComplete: that.searchComplete,
        //蓝牙连接失败
        ConnectFailed: that.connectFailed,
        //蓝牙初始化成功
        BluetoothInitSuccessed: that.bluetoothInitSuccessed,
        //蓝牙初始化失败
        BluetoothInitFailed: that.bluetoothInitFailed,
        //蓝牙状态改变
        GetBluetoothAdapterState: that.getBluetoothAdapterState
    })
  },
  connectFailed (device)  {
    this.setData({
      showDialog: false
    })
    wx.showModal({
        title: '连接失败',
        content: '点击确定将重新开始连接',
        showCancel: false,
        cancelColor: '',
        confirmText: '确定',
        success: (res) => {
            this.startSearch()
        },
        fail: (res) => {
        },
        complete: (res) => {
        },
    })
  },
  bluetoothInitSuccessed () {
    this.startSearch()
  },
  startSearch(){
    this.setData({
			bindDeviceTextInfo: '正在搜索蓝牙设备'
		})
		this.setData({
			showDialog: true
		})
    bleManager.startSearch()
  },
  bluetoothInitFailed() {
    this.setData({
      showDialog: false
    })
    wx.showModal({
        title: '蓝牙未开启',
        content: '请前往设置->蓝牙->打开蓝牙',
        showCancel: false,
        confirmText: '知道了',
        fail: (res) => {
        },
        complete: (res) => {
        },
    })
  },
  searchComplete(devicesList){
		console.log(devicesList,'devicesListdevicesList')
    //根据名称筛选设备
    let fitDevices = []
    for (var i = 0; i < devicesList.length; i++) {
        let device = devicesList[i]
        if (device.name.indexOf("PC-60F") !== -1) {
            fitDevices[fitDevices.length] = device
        }
    }
    /** 根据设备的个数判断下一步*/
    //没有合适的设备，继续搜索
    if (fitDevices.length === 0 && !this.data.isEnd) {
        bleManager.startSearch(2)
        return
    }
    const actions = []
    fitDevices.forEach(item => {
      const obj = {
        name: item.name, subname: item.deviceId, deviceId: item.deviceId
      }
      actions.push(obj)
    })
    this.setData({
      showDialog: false,
      actions: actions
    })
    this.setData({ showDevice: true });
  },
	onCancel() {
		this.setData({
			showDialog: false,
		})
	},
	onClose() {
    this.setData({ showDevice: false });
  },
	onSelect(event) {
		this.setData({
			saveDevice: event.detail
		})
		const device = this.data.bindDevice.find(item => {
			return item.name === this.data.saveDevice.name
		})
		let saveDataList = []
		// 如果绑定的有该设备
		if(device) {
			wx.showToast({
				title: '该设备已绑定',
				icon: 'none',
				duration: 3000
		  })
		} else {
			const bindDevice = { name:this.data.saveDevice.name,deviceId: this.data.saveDevice.deviceId}
			saveDataList = this.data.bindDevice.concat(bindDevice)
			this.putData(saveDataList, '保存')
		}
  },
	async get() {
		this.setData({
			bindDevice: []
		})
		try {
			this.setData({
				loading: true
			})
		  const res = await api.post('/api/user/storage/get', {
			data: {
			  'key': 'devicelist'
			}
		  })
		  if(res[0].value) {
				var array = JSON.parse(res[0].value)
				const listValue = array.filter(item => item.name === 'bloodoxygen')
				if(listValue.length > 0) {
					this.setData({
						bindDevice: listValue[0].devicelist
					})
				}
		  }
			this.setData({
				loading: false
			})
		} catch (e) {
		  console.log('get->', e)
		  return null
		}
	},
	delEq(e) {
		const name = e.currentTarget.dataset.name
		const data = this.data.bindDevice.filter(item => {
			return item.name !== name
		})
		this.putData(data, '删除')
	},
	putData(deviceIdList, type) {
		let num = [{name:'bloodoxygen',devicelist: deviceIdList}]
		num = JSON.stringify(num)
		this.doSavedevice(num, type)
	},
	// 储存设备
	async doSavedevice(result, type) {
		try {
		  await api.post('/api/user/storage/set', {
				data: {
					'key': 'devicelist',
					'value': result
				}
				})
				wx.showToast({
					title: `${type}成功`,
					icon: 'none',
					duration: 3000
				})
				this.setData({ showDevice: false });
				this.get()
			} catch (e) {
				console.log('put->', e)
			}
	  },

	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {
    
	},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
	},
	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
